/*
 * Copyright (c) 2023, 2023,yzc.cn All rights reserved.
 *
 */
package cn.yzc.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>Project: SpringBootPro - TokenUtils</p>
 * <p>Powered by yzc On 2023-11-10 11:38:30</p>
 * <p>描述：<p>
 *
 * @author yzc [yzc0415@126.com]
 * @version 1.0
 * @since 17
 */
public class TokenUtils {
    //设置有效时间
    private static final long validTime =1*60*1000;
    //设置token密钥
    private static  final String tokenSecret = "yzc";

    /**
     * 生成token
     * @param username
     * @param password
     * @return
     */
    public static String getToken(String username, String password){
          String token = "";
          //设置token的有效时间
          Date date = new Date(System.currentTimeMillis()+10*validTime);
          //密钥加密算法
         Algorithm secret = Algorithm.HMAC256(tokenSecret);
          //设置头部信息
        HashMap<String,Object> header =new HashMap<>();
        header.put("alg","HS256");
        header.put("typ","JWT");
        //携带username，password信息生成签名
        token = JWT.create().withHeader(header)
                .withClaim("username",username)
                .withClaim("password",password)
                .withExpiresAt(date)
                .sign(secret);
        return token;
    }

    /**
     * 验证token
     * @param token
     */
    public static void validToken(String token){
        try {
            Algorithm secret = Algorithm.HMAC256(tokenSecret);
            JWTVerifier verifier = JWT.require(secret).build();
            DecodedJWT jwt = verifier.verify(token);
            Map map = jwt.getClaims();
            System.out.println(map);
        }catch (JWTDecodeException e){
            System.out.println("token令牌无效");

        }catch (TokenExpiredException e){
            System.out.println("token令牌不在有效期");

        }catch (SignatureVerificationException e){
            System.out.println("token算法异常，验证签名失败");
        }
    }

    /**
     * 令牌过期刷新令牌
     * @param token
     * @return
     */
    public static String refreshToken(String token){
        DecodedJWT jwt = null;
        Algorithm secret = Algorithm.HMAC256(tokenSecret);
        JWTVerifier verifier = JWT.require(secret).build();
        try {
            jwt = verifier.verify(token);
        }catch (JWTDecodeException e){
            System.out.println("token令牌无效");

        }catch (TokenExpiredException e){
            System.out.println("token令牌不在有效期");
            //设置新的有效时间
            Date date = new Date(System.currentTimeMillis()+validTime);
            jwt= JWT.decode(token);
            //获取令牌的原始的载荷数据
            Map<String, Claim> claims =jwt.getClaims();
            //获取用户名
            String username = claims.get("username").asString();
            //获取密码
            String password =claims.get("password").asString();

            //设置头部信息
            HashMap<String,Object> header =new HashMap<>();
            header.put("alg","HS256");
            header.put("typ","JWT");


            //生成新的令牌
            String newToken = JWT.create()
                    .withHeader(header)
                    .withClaim("username",username)
                    .withClaim("password",password)
                    .withExpiresAt(date)
                    .sign(secret);
            return newToken;

        }catch (SignatureVerificationException e){
            System.out.println("token算法异常，验证签名失败");
        }
       return null;
    }

}
